package com.zhongxi.guoyuan.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.google.gson.Gson;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.adapter.ImageBannerAdapter;
import com.zhongxi.guoyuan.adapter.ad.JDViewAdapter;
import com.zhongxi.guoyuan.adapter.rewardCoin.RewardCoinAdapter;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseFragment;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.ad.AdData;
import com.zhongxi.guoyuan.entity.ad.AdResult;
import com.zhongxi.guoyuan.entity.coinStore.HotGoodsData;
import com.zhongxi.guoyuan.entity.coinStore.HotGoodsResult;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.Constants;
import com.zhongxi.guoyuan.utils.ImageUtils;
import com.zhongxi.guoyuan.utils.MyTextUtils;
import com.zhongxi.guoyuan.view.rewardCoin.RewardCoinDetailActivity;
import com.zhongxi.guoyuan.widget.ViewFlow;
import com.zhongxi.guoyuan.widget.ViewFlowIndicator;
import com.zhongxi.guoyuan.widget.ad.JDAdverView;
import com.zhongxi.guoyuan.widget.goldshop.NoScrollGridView;
import com.zhongxi.guoyuan.widget.view.MyScrollView;

import java.util.ArrayList;
import java.util.List;

public class MainRewardCoinFragment extends BaseFragment implements View.OnClickListener , MyScrollView.OnScrollListener {

    private LinearLayout linearLayout;
    private RelativeLayout scrollBody;
    private LinearLayout linearBegin;
    private LinearLayout linearStop;
    private MyScrollView myScrollView;
    private boolean isMeasured;
    private int mScrollHeight;
    private ViewFlow viewflow;
    private List<AdData> data = new ArrayList<AdData>();
    private ImageBannerAdapter mBannerAdapter;
    private List<HotGoodsData> datas = new ArrayList<HotGoodsData>();
    private Spinner spinner;
    private TextView tvMore;
    private String type;
    private int position = 0;
    private int status = 0;
    private NoScrollGridView gvList;
    private List<HotGoodsData> goodsData = new ArrayList<>();
    private RewardCoinAdapter adapter;

    private boolean isFirst;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_main_coin, container, false);
    }

    @Override
    protected void initView() {
        super.initView();
        initTitle();
        tvTitle.setText("100%返银币超市");

        //实现上拉布局悬停
        initScrollPause();

        gvList = (NoScrollGridView) getView().findViewById(R.id.gvList);
        //智能排序
        order();

        //设置高度
        FrameLayout flow = (FrameLayout) getView().findViewById(R.id.flow);
        ImageUtils.setHeight(getActivity(), Constants.flowRate, flow);

    }

    private void order() {
        //智能排序
        spinner = (Spinner) getView().findViewById(R.id.spinner);
        ArrayAdapter<String> spAdapter = new ArrayAdapter<String>(context, R.layout.simple_spinner_item);
        List<String> spList = new ArrayList<String>();
        spList.add("时间倒序");
        spList.add("价格");
        spList.add("浏览量");
        spList.add("销量");
        spAdapter.addAll(spList);
        spAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(spAdapter);
    }

    /**
     * 上下轮播
     * @param data
     */
    private void initJDScroll(List<HotGoodsData> data) {
        datas.addAll(data);

        final JDViewAdapter jddapter = new JDViewAdapter(context, datas, 1);
        final JDAdverView tbView = (JDAdverView) getView().findViewById(R.id.jdadver);
        tvMore = (TextView) getView().findViewById(R.id.tvMore);
        tvMore.setOnClickListener(this);
        tbView.setAdapter(jddapter);
        //开启线程滚动
        tbView.start();
    }

    /**
     * 左右轮播
     * @param data
     */
    private void initViewFlow(List<AdData> data) {
        /**
         * 轮播
         */
        viewflow = (ViewFlow) getView().findViewById(R.id.viewflow);
        ViewFlowIndicator viewflowdic = (ViewFlowIndicator) getView().findViewById(R.id.viewflowdic);
        viewflow.setFlowIndicator(viewflowdic);

        this.data.addAll(data);

        if(this.data.size()>0)
            viewflow.setSideBuffer(this.data.size()); // 实际图片数量
        if(mBannerAdapter == null){
            mBannerAdapter = new ImageBannerAdapter(getActivity(), this.data);
            viewflow.setAdapter(mBannerAdapter);
        }else{
            mBannerAdapter.replaceAll(this.data);
        }
        viewflow.startAutoFlowTimer();
    }

    @Override
    protected void initData() {
        super.initData();

        adapter = new RewardCoinAdapter(context, goodsData);
        gvList.setAdapter(adapter);
        //获取广告
        showAds();
    }

    /**
     * 获取广告展示
     */
    private void showAds() {
        type = "showads";
        String getStr = "&type=4";
        getServer(Url.SHOW_ADS, null,getStr, false, null, "get");
    }

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        try{
            if("showads".equals(type)){
                AdResult adResult = gson.fromJson(response, AdResult.class);
                MyApplication.getInstance().setSpValue(adResult.getSafeobj());
                if(null!=adResult.getData()&&adResult.getData().size()>0){
                    initViewFlow(adResult.getData());
                }
                getHotGoods();
            }else if("hotgoods".equals(type)){
                HotGoodsResult result = gson.fromJson(response, HotGoodsResult.class);
                MyApplication.getInstance().setSpValue(result.getSafeobj());
                if(null!=result.getData()&&result.getData().size()>0){
                    initJDScroll(result.getData());
                }
                //获取商品列表
                getGoodsList();
            }else if("goodslist".equals(type)){
                HotGoodsResult result = gson.fromJson(response, HotGoodsResult.class);
                MyApplication.getInstance().setSpValue(result.getSafeobj());
                if(pageNum == 1){
                    goodsData.clear();
                }
                if(null!=result.getData()&&result.getData().size()>0){
                    goodsData.addAll(result.getData());
                }
                adapter.notifyDataSetChanged();
                isFirst = true;
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 获取商品列表
     */
    private void getGoodsList() {
        type = "goodslist";
        String str = "&cateid="+position+"&orderby="+status+"&page="+pageNum;
        getServer(Url.MALL_GOODS_LIST, null, str, false, null, "get");
    }

    /**
     * 热推商品
     */
    private void getHotGoods() {
        type = "hotgoods";
        getServer(Url.MALL_HOT_GOODS, null, "", false, null, "get");
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        BaseResponse result = gson.fromJson(response, BaseResponse.class);
        if(null!=result.getSafeobj()&&!"".equals(result.getSafeobj()))
            MyApplication.getInstance().setSpValue(result.getSafeobj());
        if(result.getCode()==2101){
            showShortToast("数据完善中，敬请期待");
        }
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        ivBack.setOnClickListener(this);
        //跳转到商品详情页面
        gvList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getActivity(), RewardCoinDetailActivity.class);
                intent.putExtra("id", goodsData.get(position).getId());
                startActivity(intent);
            }
        });
        //筛选
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if(isFirst){
                    status = position;
                    getGoodsList();
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ivBack:
                getActivity().finish();
                break;
        }
    }

    /**
     * 上拉悬停
     */
    private void initScrollPause() {
        /**
         * 上拉悬停
         */
        linearLayout = (LinearLayout) getView().findViewById(R.id.linearLayout);
        scrollBody = (RelativeLayout) getView().findViewById(R.id.scrollBody);
        linearBegin = (LinearLayout) getView().findViewById(R.id.linearBegin);
        linearStop = (LinearLayout) getView().findViewById(R.id.linearStop);
        myScrollView = (MyScrollView) getView().findViewById(R.id.myScrollView);

        ViewTreeObserver observer = linearLayout.getViewTreeObserver();
        observer.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                if (!isMeasured) {
                    mScrollHeight = linearLayout.getMeasuredHeight();
                    isMeasured = true;
                }
                return true;
            }
        });
        myScrollView.setOnScrollListener(this);
    }

    @Override
    public void onScroll(int scrollY) {
        if(scrollY >= mScrollHeight){
            if(scrollBody.getParent() != linearStop){
                linearBegin.removeView(scrollBody);
                linearStop.addView(scrollBody);
            }
        }else{
            if(scrollBody.getParent() != linearBegin){
                linearStop.removeView(scrollBody);
                linearBegin.addView(scrollBody);
            }
        }
    }

    @Override
    public void scrollBottom() {
        if(!MyTextUtils.isFastDoubleClick()){
            pageNum++;
            getGoodsList();
        }
    }

}
